<?php

namespace app\cms\controller\api\auth;

use app\cms\controller\api\Auth;
use app\cms\model\CmsWareInbound;
use app\cms\model\cmsWareInboundDetail;
use app\cms\model\CmsWareInfo;
use think\admin\model\SystemBase;
use app\cms\service\InboundService;

/**
 * 订单
 * Class Order
 * 0 创建 1 待收货 2 确认收货 -待支付 3已支付
 * @package app\data\controller\api\auth
 */
class Order extends Auth
{
    /**
     * 获取记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {

        //get请求
        
        $map = [];



        if($this->user['usertype'] == 2){
            $map = ['receiver_code' => $this->user['ware_code'], 'deleted' => 0];
        }elseif($this->user['usertype'] == 1){
            $map = ['deleted' => 0];
        }else{
            $map = ['user_id' => $this->uuid, 'deleted' => 0];
        }
        $query = CmsWareInbound::mQuery()->in('status')->like('user_name|receiver_code#keyword');
        $result = $query->where($map)->order('id desc')->page(true, false, false, 20);
        if (count($result['list']) > 0) InboundService::instance()->buildData($result['list']);
        $this->success('获取订单数据成功！', $result);


    }

    public function get_base(){
        $warehouses = CmsWareInfo::mk()->where(['deleted' => 0])
        ->field('ware_code as code,ware_name as name')->order('sort', 'asc')->select();
       $levels = SystemBase::mk()->items('等级管理');
       $arr = [];
       foreach ($levels as $k => $value) {
            $arr[] = [
                'sort' => $k ,
                'level_code' => $value['code'],
                'level_name' => $value['name'],
                'weight' => '',
                'unit_price' => '',
                'price' => '',
                'gross_weight' => '',
                'num' => '',
            ];
       }
        $result = [
            'categorys' => array_values(SystemBase::mk()->items('种类')),
            'levels' => $arr,
            'grades' => $arr,
            'warehouses' => $warehouses
        ];
        $this->success('获取订单数据成功！', $result);
    }

    public function count()
    {
        if ($this->user['usertype'] == 2) {
            $map = ['receiver_code' => $this->user['ware_code']];
        } elseif ($this->user['usertype'] == 1) {
            $map = ['deleted' => 0];
        }else{
            $map = ['user_id' => $this->uuid];
        }
        $data = [
            '0' => CmsWareInbound::mk()->where(['deleted' => 0])->where($map)->count(),

            '1' => CmsWareInbound::mk()->where(['deleted' => 0]) ->where($map)->whereIn('status', '0,1')->count(),
            '2' => CmsWareInbound::mk()->where(['status' => 2, 'deleted' => 0])->where($map)->count(),
            '3' => CmsWareInbound::mk()->where(['status' => 3, 'deleted' => 0])->where($map)->count(),
        ];
        $this->success('成功', $data);
    }


    public function detail()
    {
        $id = input('id', 0, 'intval');
        if ($id < 1) $this->error('请选择要查看的订单！');

        if($this->user['usertype'] == 2){
            $map = ['id' => $id, 'receiver_code' => $this->user['ware_code'], 'deleted' => 0];
        } elseif ($this->user['usertype'] == 1) {
            $map = ['id' => $id, 'deleted' => 0];
        }else{
            $map = ['id' => $id, 'user_id' => $this->uuid, 'deleted' => 0];
        }
        $bill = CmsWareInbound::mk()->where($map)->find();
        if (empty($bill)) $this->error('该订单有误！');

        $cateorys = SystemBase::mk()->items('种类');
        $house = CmsWareInfo::mk()->where(['deleted' => 0])->column('ware_name', 'ware_code');

        $bill['category_name'] = $cateorys[$bill['category']]['name']  ?? '';
        $bill['depart_name'] = $house[$bill['depart_code']]  ?? '';
        $bill['receiver_name'] = $house[$bill['receiver_code']] ?? '';

        $detail = cmsWareInboundDetail::mk()->where(['bill_no' => $bill['bill_no']])->select()->toArray();
        if(!empty($detail)){
            $bill['detail'] = $detail;
        }else{
            $levels = SystemBase::mk()->items('等级管理');
            $arr = [];
            foreach ($levels as $k => $value) {
                $arr[] = [
                    'sort' => $k,
                    'level_code' => $value['code'],
                    'level_name' => $value['name'],
                    'weight' => '',
                    'unit_price' => '',
                    'gross_weight' => '',
                    'price' => '',
                    'num' => '',
                ];
            }
            $bill['detail'] = $arr;
        }
        
        $this->success('获取成功！', $bill);
    }

    public function del()
    {
        $id = input('id', 0, 'intval');
        if ($id < 1) $this->error('请选择要删除的订单！');

        $bill = CmsWareInbound::mk()->where(['id' => $id,'user_id' => $this->uuid])->find();
        if (empty($bill)) $this->error('该订单无法删除！');

        CmsWareInbound::mk()->where(['id' => $id])->delete();
        cmsWareInboundDetail::mk()->where(['bill_no' => $bill['bill_no']])->delete();
        $this->success('删除成功！');
        
    }


    public function set(){

        $data = $this->_vali([
            'total_weight.default'   => '',
            'category.require'   => '请输入种类',
            'total_num.default'   => '',
            'car_number.default'   => '',
            'depart_code.require'   => '请选择出发地',
            'receiver_code.require'   => '请选择目的地',
            'detail.default'      => '',
            'type.default'      => '',
            'remark.default'      => '',
        ], 'post');

        $data['user_id'] = $this->uuid;
        $data['user_name'] = $this->user['nickname'];
        if(empty($data['user_name'])){
            $this->error('请到个人中心输入名称！');
        }
        $bill_no = InboundService::instance()->generatorCode();
        $data['bill_no'] = $bill_no;

        if($data['type'] == 1){
            $data['status'] = 1;
            $details = [];
            $total_weight = 0;
            $total_num = 0;
            $total_price = 0;
            foreach ($data['detail'] as $k => $value) {
                if(empty($value['weight']) || empty($value['num'])){
                    continue;
                }
                $details[$k]['weight'] = $value['weight'];
                $details[$k]['num'] = $value['num'];
                $details[$k]['gross_weight'] = $value['gross_weight'];
                $details[$k]['unit_price'] = $value['unit_price'];
                $details[$k]['price'] = $value['gross_weight'] * $value['unit_price'];
                $details[$k]['level_name'] = $value['level_name'];
                $details[$k]['level_code'] = $value['level_code'];
                $details[$k]['bill_no'] = $bill_no;
                $details[$k]['created_by'] = $this->user['nickname'];
                $total_weight += $value['gross_weight'];
                $total_price += $value['gross_weight'] * $value['unit_price'];
                $total_num += $value['num'];
            }
            $data['total_price'] = $total_price;
            $data['total_weight'] = $total_weight; 
            $data['total_num'] =  $total_num;

        }

        if(CmsWareInbound::mk()->save($data)){

            if(!empty($details)){
                cmsWareInboundDetail::mk()->saveAll($details);
            }
            
            $this->success('成功', $data);
        }

        $this->error('添加失败');


       

    }

    public function pay(){
        $data = $this->_vali([
            'id.require'   => '请输入id',
            'bill_no.require'   => '请输入Billno'
        ], 'post');

        $bill = CmsWareInbound::mk()->where(['id' => $data['id'], 'bill_no' => $data['bill_no']])->find();
        if (empty($bill)) $this->error('该订单不存在！');

        if(CmsWareInbound::mk()->where(['id' => $data['id'], 'bill_no' => $data['bill_no']])->update(['status' => 3])){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }

    }

    public function pick()
    {
        $data = $this->_vali([
            'id.require'   => '请输入id',
            'bill_no.require'   => '请输入Billno',
            'detail.require'   => '请输入明细',
            'type.default'      => '',
        ], 'post');

        $bill = CmsWareInbound::mk()->where(['id' => $data['id'], 'bill_no' => $data['bill_no']])->find();
        if (empty($bill)) $this->error('该订单不存在！');

    
        if(!empty($data['detail'])){

            $details = [];
            $total_weight = 0;
            $total_num = 0;
            $total_price = 0;
            foreach ($data['detail'] as $k => $value) {

                if (empty($value['weight']) || empty($value['num'])) {
                    continue;
                }

                $unit_price = floatval($value['unit_price']) ?? 0;
                $gross_weight = floatval($value['gross_weight']) ?? 0;

                $details[$k]['weight'] = $value['weight'];

                $details[$k]['num'] = $value['num'];
                $details[$k]['gross_weight'] = $gross_weight;
                $details[$k]['unit_price'] = $unit_price;
                $details[$k]['price'] = $gross_weight * $unit_price;
                $details[$k]['level_name'] = $value['level_name'];
                $details[$k]['level_code'] = $value['level_code'];
                $details[$k]['bill_no'] = $bill['bill_no'];
                $details[$k]['created_by'] = $this->user['nickname'];
                $total_weight += $gross_weight;
                $total_price += $gross_weight * $unit_price;
                $total_num += $value['num'];
            }

            CmsWareInbound::mk()->where(['id' => $data['id'], 'bill_no' => $data['bill_no']])->update(['status' => 2, 'total_price' => $total_price]);
            cmsWareInboundDetail::mk()->where(['bill_no' => $bill['bill_no']])->delete();
            cmsWareInboundDetail::mk()->saveAll($details);
            $this->success('操作成功');
        }

        $this->error('失败');
    }

  
}